package es.cazadoresmadridejos.beans.dao.payment.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import es.cazadoresmadridejos.beans.dao.payment.PaymentDao;
import es.cazadoresmadridejos.common.bean.dao.impl.DaoImpl;
import es.cazadoresmadridejos.model.Partner;
import es.cazadoresmadridejos.model.Payment;

@SuppressWarnings("unchecked")
@Repository("paymentDao")
public class PaymentDaoImpl extends DaoImpl<Payment> implements PaymentDao{

	@Override
	public Payment newInstance() {
		return new Payment();
	}

	@Override
	public List<Payment> findAllByReason(final Long idReason) {
		return (List<Payment>) getHibernateTemplate().execute(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {

				StringBuilder hql = new StringBuilder();
				hql
				.append("select p ")
				.append(" from Payment p ")
				.append(" where p.reason.id = :reasonId ")
				.append(" order by p.type, p.partner.lastName ");

				Query query = session.createQuery(hql.toString());

				query.setLong("reasonId",idReason);

				return query.list();
			}
		});
	}

	@Override
	public List<Partner> findAllNotIncludedByReason(final Long idReason) {
		// TODO Auto-generated method stub
		return (List<Partner>) getHibernateTemplate().execute(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {

				StringBuilder hql = new StringBuilder();
				hql
				.append(" select p ")
				.append(" from Partner p ")
				.append(" where p.id not in (select pay.partner.id from Payment pay where pay.reason.id = :reasonId) ")
				.append(" 	and p.active = 1 ")
				.append(" 	and p.role != 'ADMINISTRADOR' ")
				.append(" order by p.hunterType, p.lastName ");

				Query query = session.createQuery(hql.toString());

				query.setLong("reasonId",idReason);

				return query.list();			
			}
		});
	}

}
